<template>
  <div class="table-list">
    <flexbox
      align="center"
      justify="flex-end"
      style="margin-bottom: 10px">
      <el-button
        icon="el-icon-plus"
        type="primary"
        class="xr-btn--orange"
        @click="addFile">
        上传附件
      </el-button>
    </flexbox>

    <el-table
      :data="list"
      :height="400"
      class="file-table"
      stripe
      style="width: 100%;border: 1px solid #E6E6E6;">
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        show-overflow-tooltip />
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <flexbox>
            <el-button
              type="text"
              @click.native="handleFile('preview', scope)">预览</el-button>
            <el-button
              type="text"
              @click.native="handleFile('download', scope)">下载</el-button>
            <el-button
              :disabled="scope.row.readOnly == 1"
              type="text"
              @click.native="handleFile('update', scope)">重命名</el-button>
            <el-button
              :disabled="scope.row.readOnly == 1"
              type="text"
              @click.native="handleFile('delete', scope)">删除</el-button>
          </flexbox>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="editDialog"
      title="编辑"
      width="30%">
      <el-form :model="editForm">
        <el-form-item
          label="新名称"
          label-width="100">
          <el-input
            v-model="editForm.name"
            autocomplete="off" />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

    <input
      v-if="showFileHook"
      ref="detailImgInput"
      type="file"
      class="file-input"
      @change="upLoad">
  </div>
</template>

<script>
import {
  jxcFileAddOrUpdateAPI,
  jxcFileQueryListAPI
} from '@/api/jxc/file'

import {
  adminFileUploadAPI,
  adminFileDeleteByIdAPI,
  adminFileRenameFileAPI,
  adminFileDownByUrlAPI
} from '@/api/admin/file'

import { fileSize, canPreviewFile, wkPreviewFile, downloadFileWithBuffer } from '@/utils'

export default {
  name: 'TabFile',
  inheritAttrs: false,
  props: {
    label: {
      type: [String, Number],
      required: true
    },
    batchId: {
      type: String
    },
    detailData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      list: [],
      fieldList: [
        { prop: 'name', width: '200', label: '附件名称' },
        { prop: 'size', width: '100', label: '附件大小' },
        { prop: 'createUserName', width: '100', label: '上传人' },
        { prop: 'createTime', width: '200', label: '上传时间' },
        { prop: 'source', width: '100', label: '来源' }
      ],

      editForm: {
        name: ''
      },
      showFileHook: true,
      editDialog: false
    }
  },
  watch: {
    detailData: {
      handler() {
        if (this.label && this.batchId) {
          this.getList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getList() {
      jxcFileQueryListAPI({
        jxcBatchId: this.batchId,
        label: this.label
      }).then(res => {
        this.list = res.data.fileList || []
        this.list = res.data.map(item => {
          item.size = fileSize(item.size)
          return item
        })
      }).catch(() => {
      })
    },

    addFile() {
      this.$refs.detailImgInput.click()
    },
    upLoad(event) {
      const files = Array.from(event.target.files)

      if (files.length === 0) return
      for (let index = 0; index < files.length; index++) {
        this.$wkUploadFile.upload({
          request: adminFileUploadAPI,
          file: files[index],
          params: {
            batchId: this.batchId
          }
        }).then(data => {
          const { res } = data
          this.showFileHook = false
          this.$nextTick(() => {
            this.showFileHook = true
          })
          jxcFileAddOrUpdateAPI({
            batchId: res.data.batchId,
            jxcBatchId: this.batchId,
            label: this.label
          }).then(() => {
            this.getList()
          }).catch(() => {})
        }).catch(() => {})
      }
    },

    /**
     * control cell
     */
    handleFile(type, scope) {
      switch (type) {
        case 'preview':
          if (canPreviewFile(scope.row.name)) {
            wkPreviewFile(scope.row.url, scope.row.name)
          } else {
            this.$bus.emit('preview-image-bus', {
              index: scope.$index,
              data: this.list
            })
          }
          break
        case 'download':
          adminFileDownByUrlAPI(scope.row.url).then(res => {
            const blob = new Blob([res.data], {
              type: ''
            })
            downloadFileWithBuffer(blob, scope.row.name)
          }).catch(() => {})
          break
        case 'update':
          this.editForm.data = scope
          this.editForm.name = scope.row.name
          this.editDialog = true
          break
        case 'delete':
          this.$confirm('您确定要删除该文件吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log(scope.row)
            adminFileDeleteByIdAPI(scope.row.fileId).then(() => {
              this.list.splice(scope.$index, 1)
              this.$message.success('操作成功')
            }).catch(() => {})
          }).catch(() => {
            this.$message.info('已取消操作')
          })
          break
      }
    },

    confirmEdit() {
      if (this.editForm.name) {
        adminFileRenameFileAPI({
          fileId: this.editForm.data.row.fileId,
          name: this.editForm.name
        }).then(res => {
          this.$message.success('编辑成功')
          this.editDialog = false
          const item = this.list[this.editForm.data.$index]
          item.name = this.editForm.name
        }).catch(() => {})
      }
    }
  }
}
</script>

<style scoped lang="scss">
.table-list {
  padding: 15px;
}
.file-input {
  width: 0;
  height: 0;
  visibility: hidden;
}
</style>
